import axios from 'axios'
import { Message } from 'element-ui';
import router from '../src/router';

/*封装客户端请求拦截器*/
axios.interceptors.request.use((config)=>{
  console.log(`请求【${config.url}】${config.needLogin?'需要':'不需要'}登录`);
  if(config.needLogin){
    if(window.sessionStorage.getItem('access_token')){
        config.headers.Authorization = 'Bearer '+ window.sessionStorage.getItem('access_token');
    }
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

/*封装服务端响应拦截器*/
axios.interceptors.response.use(success=>{
    if (success.data.status == 200 && success.data.status == 500){
        Message.error({message:success.data.msg})
        return;
    }
    if (success.status && success.status == 200 && success.data.status == 500){
        Message.error({message:success.data.msg})
        return;
    }
    if (success.status && success.status == 200 && success.data.code == 401){
        return doRequest(success);
    }
    if (success.status && success.status == 200 && success.data.code == 403){
        Message.error({message:'权限不足,请联系管理员!'})
        router.replace({path:'/'});
        return;
    }
    // msg 自定义消息
    if (success.data.msg){
        Message.success({message:success.data.msg})
    }
    // 下载文件资源 type:文件类型
    if(success.data.type){
        return success;
    }
    return success.data;
},error => {
    if (error.response.status == 504){
        Message.error({message:'访问程序出差啦,请联系运维人员。'})
        console.log("尊敬的程序员先生网关挂掉啦！");
    }else if (error.response.status == 403){
        Message.error({message:'权限不足,请联系管理员！'})
    }else if (error.response.status == 401){
        return doRequest(success);
    }else if (error.response.status == 500 && error.response.data.code == 504){
        Message.error({message:error.response.data.message})
        console.log(error.response.data)
    }else {
        if (error.response.data.msg){
            Message.error({message:error.response.data.msg})
        }else {
            Message.error({message:'未知错误！'})
        }
    }
    return;
})

async function doRequest (error) {
  try {
    console.log(error.config)
    await getNewToken()
    const res = await service.request(error.config)
    return res;
  } catch(err) {
    sessionStorage.clear();
    router.replace({
      path:"/"
    });
    return err;
  }
}

async function getNewToken() {
  postRequestRefreshToken('/authorization/oauth/token?grant_type=refresh_token&client_id=211214C8TND4C8SW&client_secret=123456&refresh_token='+sessionStorage.getItem('refresh_token')).then(resp=>{
      if (resp){
          window.sessionStorage.setItem("access_token",resp.data.access_token);
          window.sessionStorage.setItem("refresh_token",resp.data.refresh_token);
      }
  })
}

/*url前缀*/
let base = '';
/*是否需要登录*/
let needLogin = true;

/*封装请求方式,这里封装两个post请求,一个专门用来登录使用key-value的方式传参,
因为Spring Security登录默认不支持Json参数*/
export const postKeyValueRequest=(url,params)=>{
    return axios({
        needLogin: false,
        method:'post',
        url:`${base}${url}`,
        data:params,
        transformRequest:[function (data) {
            let ret = '';
            for (let i in data){
                ret += encodeURIComponent(i) + "=" + encodeURIComponent(data[i]) + "&"
            }
            return ret;
        }],
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    });
}

// RefreshToken请求
export const postRequestRefreshToken=(url,params)=>{
    return axios({
        needLogin: false,
        method: 'post',
        url:`${base}${url}`,
        data: params
    });
}
// Post请求
export const postRequest=(url,params)=>{
    return axios({
        needLogin: true,
        method: 'post',
        url:`${base}${url}`,
        data: params
    });
}
// Get请求
export const getRequest=(url,params)=>{
    return axios({
        needLogin: true,
        method:'get',
        url:`${base}${url}`,
        data:params
    });
}
// Put请求
export const putRequest=(url,params)=>{
    return axios({
        needLogin: true,
        method:'put',
        url:`${base}${url}`,
        data:params
    });
}
// Delete请求
export const deleteRequest=(url,params)=>{
    return axios({
        needLogin: true,
        method:'delete',
        url:`${base}${url}`,
        data:params
    });
}
/*唯一验证请求*/
export const validateCode=(url,params)=>{
    return axios({
        needLogin: true,
        method:'get',
        url:`${base}${url}`,
        data:params
    });
}

// 文件类型
const mimeMap = {
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    xls: 'application/vnd.ms-excel',
    zip: 'application/zip',
    jpg: 'image/jpg',
    jpeg: 'image/jpeg',
    png: 'image/png',
    doc: 'application/msword',
    docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    ppt: 'application/vnd.ms-powerpoint',
    txt: 'text/plain',
    pdf: 'application/pdf'
  }
// 下载附件请求
export function downloadAttachment(path, param) {
    var url = base + path + param
    axios({
      needLogin: true,
      url: url,
      method: 'get',
      responseType: 'blob'
    }).then(res => {
        if(res.data.type === "application/json"){
          // 说明是对象数据--下载失败
          let reader = new FileReader();
          reader.onload = function(event){
            let result = JSON.parse(reader.result);
            console.log(result)
            Message.error({message:result.msg})
          }
          reader.readAsText(res.data);
        }else{
         // 说明是文件流--下载成功
         Message.success({message:"下载成功"})
         resolveBlob(res, res.data.type)
        }
      })
  }

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export const resolveBlob=(res, mimeType)=> {
    const aLink = document.createElement('a')
    var blob = new Blob([res.data], { type: mimeType })
    // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
    var contentDisposition = decodeURI(res.headers['content-disposition'])
    var result = patt.exec(contentDisposition)
    var fileName = result[1]
    fileName = fileName.replace(/\"/g, '')
    aLink.href = URL.createObjectURL(blob)
    aLink.setAttribute('download', fileName) // 设置下载文件名称
    document.body.appendChild(aLink)
    aLink.click()
    document.body.removeChild(aLink);
}
